package com.wjj.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.wjj.common.core.constant.CacheNames;
import com.wjj.common.core.constant.UserConstants;
import com.wjj.common.core.domain.dto.UserDTO;
import com.wjj.common.core.exception.ServiceException;
import com.wjj.common.core.service.UserService;
import com.wjj.common.core.utils.MapstructUtils;
import com.wjj.common.core.utils.SpringUtils;
import com.wjj.common.core.utils.StreamUtils;
import com.wjj.common.core.utils.StringUtils;
import com.wjj.common.mybatis.core.page.PageQuery;
import com.wjj.common.mybatis.core.page.TableDataInfo;
import com.wjj.common.satoken.utils.LoginHelper;
import com.wjj.system.domain.SysUser;
import com.wjj.system.domain.SysUserRole;
import com.wjj.system.domain.bo.SysRoleBo;
import com.wjj.system.domain.bo.SysUserBo;
import com.wjj.system.domain.vo.SysRoleVo;
import com.wjj.system.domain.vo.SysUserExportVo;
import com.wjj.system.domain.vo.SysUserVo;
import com.wjj.system.mapper.*;
import com.wjj.system.service.ISysUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 用户 业务层处理
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService, UserService {

    private final SysRoleMapper roleMapper;
    private final SysUserRoleMapper userRoleMapper;

    @Override
    public TableDataInfo<SysUserVo> selectPageUserList(SysUserBo user, PageQuery pageQuery) {
        Page<SysUserVo> page = mapper.xmlPaginate("selectPageUserList", pageQuery.build(), this.buildQueryWrapper(user));
        return TableDataInfo.build(page);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUserExportVo> selectUserExportList(SysUserBo user) {
        Map<String, Object> params = user.getParams();
        QueryWrapper wrapper = QueryWrapper.create();
        wrapper.eq(SysUser::getUserId, user.getUserId(), ObjectUtil.isNotNull(user.getUserId()))
            .like(SysUser::getUserName, user.getUserName(), StringUtils.isNotBlank(user.getUserName()))
            .eq(SysUser::getStatus, user.getStatus(), StringUtils.isNotBlank(user.getStatus()))
            .like(SysUser::getPhonenumber, user.getPhonenumber(), StringUtils.isNotBlank(user.getPhonenumber()))
            .between(SysUser::getCreateTime, params.get("beginTime"), params.get("endTime"), params.get("beginTime") != null && params.get("endTime") != null)
            .orderBy(SysUser::getUserId, true);
        if (StringUtils.isNotBlank(user.getExcludeUserIds())) {
            wrapper.notIn(SysUser::getUserId, StringUtils.splitTo(user.getExcludeUserIds(), Convert::toLong));
        }
        List<SysUser> sysUsers = mapper.selectListByQuery(wrapper);
        return MapstructUtils.convert(sysUsers, SysUserExportVo.class);
    }

    private QueryWrapper buildQueryWrapper(SysUserBo user) {
        Map<String, Object> params = user.getParams();
        QueryWrapper wrapper = QueryWrapper.create();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
            .eq("u.user_id", user.getUserId(), ObjectUtil.isNotNull(user.getUserId()))
            .like("u.user_name", user.getUserName(), StringUtils.isNotBlank(user.getUserName()))
            .eq("u.status", user.getStatus(), StringUtils.isNotBlank(user.getStatus()))
            .like("u.phonenumber", user.getPhonenumber(), StringUtils.isNotBlank(user.getPhonenumber()))
            .between("u.create_time", params.get("beginTime"), params.get("endTime"), params.get("beginTime") != null && params.get("endTime") != null)
            .orderBy("u.user_id", true);
        if (StringUtils.isNotBlank(user.getExcludeUserIds())) {
            wrapper.notIn("u.user_id", StringUtils.splitTo(user.getExcludeUserIds(), Convert::toLong));
        }
        return wrapper;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public TableDataInfo<SysUserVo> selectAllocatedList(SysUserBo user, PageQuery pageQuery) {
        List<SysUserVo> sysUserVos = mapper.selectAllocatedList(user, pageQuery);
        Long total = mapper.selectAllocatedCount(user);
        Page<SysUserVo> page = new Page<>(sysUserVos, pageQuery.getPageNum(), pageQuery.getPageSize(), total);
        return TableDataInfo.build(page);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public TableDataInfo<SysUserVo> selectUnallocatedList(SysUserBo user, PageQuery pageQuery) {
        List<SysUserVo> sysUserVos = mapper.selectUnallocatedList(user, pageQuery);
        Long total = mapper.selectUnallocatedCount(user);
        Page<SysUserVo> page = new Page<>(sysUserVos, pageQuery.getPageNum(), pageQuery.getPageSize(), total);
        return TableDataInfo.build(page);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserByUserName(String userName) {
        SysUser sysUser = mapper.selectOneByQuery(QueryWrapper.create().eq(SysUser::getUserName, userName));
        return MapstructUtils.convert(sysUser, SysUserVo.class);
    }

    /**
     * 通过手机号查询用户
     *
     * @param phonenumber 手机号
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserByPhonenumber(String phonenumber) {
        SysUser sysUser = mapper.selectOneByQuery(QueryWrapper.create().eq(SysUser::getPhonenumber, phonenumber));
        return MapstructUtils.convert(sysUser, SysUserVo.class);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserById(Long userId) {
        SysUser sysUser = mapper.selectOneById(userId);
        SysUserVo user = MapstructUtils.convert(sysUser, SysUserVo.class);
        if (ObjectUtil.isNull(user)) {
            return user;
        }
        user.setRoles(roleMapper.selectRolesByUserId(user.getUserId()));
        return user;
    }

    /**
     * 通过用户ID串查询用户
     *
     * @param userIds 用户ID串
     * @param deptId  部门id
     * @return 用户列表信息
     */
    @Override
    public List<SysUserVo> selectUserByIds(List<Long> userIds, Long deptId) {
        return mapper.selectUserList(userIds);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId) {
        List<SysRoleVo> list = roleMapper.selectRolesByUserId(userId);
        if (CollUtil.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return StreamUtils.join(list, SysRoleVo::getRoleName);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUserBo user) {
        boolean exist = mapper.selectCountByQuery(QueryWrapper.create()
            .eq(SysUser::getUserName, user.getUserName())
            .ne(SysUser::getUserId, user.getUserId(), ObjectUtil.isNotNull(user.getUserId()))) > 0;
        return !exist;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     */
    @Override
    public boolean checkPhoneUnique(SysUserBo user) {
        boolean exist = mapper.selectCountByQuery(QueryWrapper.create()
            .eq(SysUser::getPhonenumber, user.getPhonenumber())
            .ne(SysUser::getUserId, user.getUserId(), ObjectUtil.isNotNull(user.getUserId()))) > 0;
        return !exist;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     */
    @Override
    public boolean checkEmailUnique(SysUserBo user) {
        boolean exist = mapper.selectCountByQuery(QueryWrapper.create()
            .eq(SysUser::getEmail, user.getEmail())
            .ne(SysUser::getUserId, user.getUserId(), ObjectUtil.isNotNull(user.getUserId()))) > 0;
        return !exist;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userId 用户ID
     */
    @Override
    public void checkUserAllowed(Long userId) {
        if (ObjectUtil.isNotNull(userId) && LoginHelper.isSuperAdmin(userId)) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            return;
        }
        if (LoginHelper.isSuperAdmin()) {
            return;
        }
        if (mapper.countUserById(userId) == 0) {
            throw new ServiceException("没有权限访问用户数据！");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUserBo user) {
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        // 新增用户信息
        int rows = mapper.insert(sysUser);
        user.setUserId(sysUser.getUserId());
        // 新增用户与角色管理
        insertUserRole(user, false);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUserBo user) {
        user.setCreateBy(0L);
        user.setUpdateBy(0L);
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        return mapper.insert(sysUser) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = CacheNames.SYS_NICKNAME, key = "#user.userId")
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUserBo user) {
        // 新增用户与角色管理
        insertUserRole(user, true);
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        // 防止错误更新后导致的数据误删除
        int flag = mapper.update(sysUser);
        if (flag < 1) {
            throw new ServiceException("修改用户" + user.getUserName() + "信息失败");
        }
        return flag;
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        insertUserRole(userId, roleIds, true);
    }

    /**
     * 修改用户状态
     *
     * @param userId 用户ID
     * @param status 帐号状态
     * @return 结果
     */
    @Override
    public int updateUserStatus(Long userId, String status) {
        boolean update = UpdateChain.of(SysUser.class)
            .set(SysUser::getStatus, status)
            .eq(SysUser::getUserId, userId)
            .update();
        return update ? 1 : 0;
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheNames.SYS_NICKNAME, key = "#user.userId")
    @Override
    public int updateUserProfile(SysUserBo user) {
        boolean update = UpdateChain.of(SysUser.class)
            .set(SysUser::getNickName, user.getNickName(), ObjectUtil.isNotNull(user.getNickName()))
            .set(SysUser::getPhonenumber, user.getPhonenumber())
            .set(SysUser::getEmail, user.getEmail())
            .set(SysUser::getSex, user.getSex())
            .eq(SysUser::getUserId, user.getUserId())
            .update();
        return update ? 1 : 0;
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, Long avatar) {
        return UpdateChain.of(SysUser.class)
            .set(SysUser::getAvatar, avatar)
            .eq(SysUser::getUserId, userId)
            .update();
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        boolean update = UpdateChain.of(SysUser.class)
            .set(SysUser::getPassword, password)
            .eq(SysUser::getUserId, userId)
            .update();
        return update ? 1 : 0;
    }

    /**
     * 新增用户角色信息
     *
     * @param user  用户对象
     * @param clear 清除已存在的关联数据
     */
    private void insertUserRole(SysUserBo user, boolean clear) {
        this.insertUserRole(user.getUserId(), user.getRoleIds(), clear);
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     * @param clear   清除已存在的关联数据
     */
    private void insertUserRole(Long userId, Long[] roleIds, boolean clear) {
        if (ArrayUtil.isNotEmpty(roleIds)) {
            // 判断是否具有此角色的操作权限
            List<SysRoleVo> roles = roleMapper.selectRoleList(new SysRoleBo());
            if (CollUtil.isEmpty(roles)) {
                throw new ServiceException("没有权限访问角色的数据");
            }
            List<Long> roleList = StreamUtils.toList(roles, SysRoleVo::getRoleId);
            if (!LoginHelper.isSuperAdmin(userId)) {
                roleList.remove(UserConstants.SUPER_ADMIN_ID);
            }
            List<Long> canDoRoleList = StreamUtils.filter(List.of(roleIds), roleList::contains);
            if (CollUtil.isEmpty(canDoRoleList)) {
                throw new ServiceException("没有权限访问角色的数据");
            }
            if (clear) {
                // 删除用户与角色关联
                userRoleMapper.deleteByQuery(QueryWrapper.create().eq(SysUserRole::getUserId, userId));
            }
            // 新增用户与角色管理
            List<SysUserRole> list = StreamUtils.toList(canDoRoleList, roleId -> {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                return ur;
            });
            userRoleMapper.insertBatch(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteByQuery(new QueryWrapper().eq(SysUserRole::getUserId, userId));
        // 防止更新失败导致的数据删除
        int flag = mapper.deleteById(userId);
        if (flag < 1) {
            throw new ServiceException("删除用户失败!");
        }
        return flag;
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(userId);
            checkUserDataScope(userId);
        }
        List<Long> ids = List.of(userIds);
        // 删除用户与角色关联
        userRoleMapper.deleteByQuery(new QueryWrapper().in(SysUserRole::getUserId, ids));
        // 防止更新失败导致的数据删除
        boolean flag = this.removeByIds(ids);
        if (!flag) {
            throw new ServiceException("删除用户失败!");
        }
        return 1;
    }


    /**
     * 通过用户ID查询用户账户
     *
     * @param userId 用户ID
     * @return 用户账户
     */
    @Cacheable(cacheNames = CacheNames.SYS_USER_NAME, key = "#userId")
    @Override
    public String selectUserNameById(Long userId) {
        SysUser sysUser = mapper.selectOneByQuery(QueryWrapper.create()
            .select(SysUser::getUserName).eq(SysUser::getUserId, userId));
        return ObjectUtil.isNull(sysUser) ? null : sysUser.getUserName();
    }

    /**
     * 通过用户ID查询用户账户
     *
     * @param userId 用户ID
     * @return 用户账户
     */
    @Override
    @Cacheable(cacheNames = CacheNames.SYS_NICKNAME, key = "#userId")
    public String selectNicknameById(Long userId) {
        SysUser sysUser = mapper.selectOneByQuery(QueryWrapper.create()
            .select(SysUser::getNickName).eq(SysUser::getUserId, userId));
        return ObjectUtil.isNull(sysUser) ? null : sysUser.getNickName();
    }

    /**
     * 通过用户ID查询用户账户
     *
     * @param userIds 用户ID 多个用逗号隔开
     * @return 用户账户
     */
    @Override
    public String selectNicknameByIds(String userIds) {
        List<String> list = new ArrayList<>();
        for (Long id : StringUtils.splitTo(userIds, Convert::toLong)) {
            String nickname = SpringUtils.getAopProxy(this).selectNicknameById(id);
            if (StringUtils.isNotBlank(nickname)) {
                list.add(nickname);
            }
        }
        return String.join(StringUtils.SEPARATOR, list);
    }

    /**
     * 通过用户ID查询用户手机号
     *
     * @param userId 用户id
     * @return 用户手机号
     */
    @Override
    public String selectPhonenumberById(Long userId) {
        SysUser sysUser = mapper.selectOneByQuery(QueryWrapper.create()
            .select(SysUser::getPhonenumber).eq(SysUser::getUserId, userId));
        return ObjectUtil.isNull(sysUser) ? null : sysUser.getPhonenumber();
    }

    /**
     * 通过用户ID查询用户邮箱
     *
     * @param userId 用户id
     * @return 用户邮箱
     */
    @Override
    public String selectEmailById(Long userId) {
        SysUser sysUser = mapper.selectOneByQuery(QueryWrapper.create()
            .select(SysUser::getEmail).eq(SysUser::getUserId, userId));
        return ObjectUtil.isNull(sysUser) ? null : sysUser.getEmail();
    }

    @Override
    public List<UserDTO> selectListByIds(List<Long> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return List.of();
        }
        List<SysUser> list = mapper.selectListByQuery(QueryWrapper.create()
            .select(SysUser::getUserId, SysUser::getUserName, SysUser::getNickName)
            .eq(SysUser::getStatus, UserConstants.USER_NORMAL)
            .in(SysUser::getUserId, userIds, CollUtil.isNotEmpty(userIds)));
        return BeanUtil.copyToList(list, UserDTO.class);
    }

    @Override
    public List<Long> selectUserIdsByRoleIds(List<Long> roleIds) {
        List<SysUserRole> userRoles = userRoleMapper.selectListByQuery(
            QueryWrapper.create().in(SysUserRole::getRoleId, roleIds));
        return StreamUtils.toList(userRoles, SysUserRole::getUserId);
    }

}
